import { world } from "@minecraft/server";
import { Timer } from "@sapi-game/gameComponent/common/timer/timer";
import { GameComponent } from "@sapi-game/main";
import { PKParkourState } from "../pkParkourState";
import { PKGameOverController } from "./gameOverController";

export class PKDaemon extends GameComponent<PKParkourState> {
    override onAttach(): void {
        const timer = this.state.getComponent(Timer);
        //显示挑战剩余时间
        this.subscribe(timer.events.tick, (t) => {
            const state = this.state.isTest ? "测试" : "挑战";
            this.context.blue.team.runCommand(
                `title @s actionbar §b[你是蓝队] §r${state}剩余时间 : §6§l${t.remainingTime}§r 秒`
            );
            this.context.red.team.runCommand(
                `title @s actionbar §c[你是红队] §r${state}剩余时间 : §6§l${t.remainingTime}§r 秒`
            );
        });
        //死后出生时传送
        this.subscribe(world.afterEvents.playerSpawn, (t) => {
            const ans = this.context.groupSet.findById(t.player.id);
            if (ans?.player.player) {
                if (ans.group == this.state.team) {
                    //是当前上场队伍
                    this.state.spawnActivePlayer(ans.player.player);
                } else {
                    this.state.tpToSpawn(ans.player.player);
                }
            }
        });
        //死了生命-1
        this.subscribe(world.afterEvents.entityDie, (t) => {
            const ans = this.context.groupSet.findById(t.deadEntity.id);
            if (ans?.player.player && ans.group == this.state.team) {
                this.state.getComponent(PKGameOverController).onDie(ans.player.player);
            }
        });
    }
}
